import { defineConfig, splitVendorChunkPlugin } from 'vite';
import react from '@vitejs/plugin-react';
import svgr from 'vite-plugin-svgr';
import utils from './tasks/utils';
import getIPAddress from './tasks/get-ip-address';
import pkg from './package.json';

import {
    removePlugin,
    htmlPlugin,
    endPlugin,
    docScssPlugin,
} from './tasks/plugins';
import Parser from 'yargs-parser';

const env = process.env.ENV;
const ipAddress = getIPAddress() || null;
const ipPort = pkg.project.port || 3008;
const { useMinify } = pkg.project;
const { resolve } = utils;

let baseURL = pkg.project.env[env].baseURL;

const assetsURL = pkg.project.env[env].assetsURL;

// 云构建的时候，动态构建baseURL
// 比如 https://dev.g.alicdn.com/b-design/b-design-antd-lite/0.0.1/index.js

// 可以替换成
// https://${cdnPrefix}g.alicdn.com/${BUILD_GIT_GROUP}/${BUILD_GIT_PROJECT}/${def_publish_version}/index.js
if (process.env.BUILD_ENV) {
    const { BUILD_GIT_GROUP, BUILD_GIT_PROJECT } = process.env;
    const buildArgv = Parser(process.env.BUILD_ARGV_STR || []);
    const { def_publish_env, def_publish_version } = buildArgv;

    const cdnPrefix = def_publish_env === 'daily' ? 'dev.' : '';
    baseURL = `https://${cdnPrefix}g.alicdn.com/${BUILD_GIT_GROUP}/${BUILD_GIT_PROJECT}/${def_publish_version}/`;

    // console.log(baseURL);
}

const pluginArr = [
    // react(), // causes vite warning that "this is undefined"
    docScssPlugin(),
    svgr(),
    splitVendorChunkPlugin(),
    htmlPlugin(),
];

export default async ({ command, mode }) => {
    return defineConfig({
        base: baseURL,
        root: resolve('./src'),
        publicDir: resolve('./src/static'),

        server: {
            host: ipAddress,
            port: ipPort,
            strictPort: true,
            open: true,
            hmr: {
                protocol: 'ws',
                host: ipAddress,
            },
            watch: {
                usePolling: true,
            },

            // proxy: {
            //     '/v1': {
            //         target: 'https://222.37.69.33',
            //         changeOrigin: true,
            //         secure: false,
            //         rewrite: (path) => path.replace(/^\/v1/, '/v1'),
            //         configure: (proxy, options) => {
            //             proxy.on('proxyReq', (proxyReq, req, res) => {
            //                 const originalHost = req.headers.host;
            //                 // console.log(originalHost, 'originalHost');
            //                 if (originalHost) {
            //                     // 生成新的目标主机名
            //                     const targetHost = originalHost.replace(
            //                         '192.168.1.126:1234',
            //                         '101.37.69.11'
            //                         // 'midjourney-lab-backend.fcv3.1672416207091773.cn-hangzhou.fc.devsapp.net'
            //                     );
            //                     // const targetHost = originalHost.replace(
            //                     //     'frontend',
            //                     //     'backend'
            //                     // );
            //                     // console.log(targetHost, 'targetHost');

            //                     // 修改请求头
            //                     proxyReq.setHeader('host', targetHost);

            //                     // 修改目标协议和主机（保持路径不变）
            //                     const originalTarget = proxy.options.target;
            //                     try {
            //                         const targetUrl = new URL(originalTarget);
            //                         const originalHostUrl = new URL(
            //                             `http://${originalHost}`
            //                         );

            //                         // 构造新的目标URL
            //                         targetUrl.protocol =
            //                             originalHostUrl.protocol;
            //                         targetUrl.host = targetHost;

            //                         proxy.options.target = targetUrl.toString();
            //                     } catch (e) {
            //                         console.error(
            //                             'Error constructing target URL:',
            //                             e
            //                         );
            //                     }
            //                 }
            //             });

            //             proxy.on('proxyRes', (proxyRes, req, res) => {
            //                 const target = proxy.options.target;
            //                 proxyRes.headers['x-proxy-target'] = target;
            //                 console.log('实际代理目标:', target);
            //             });
            //         },
            //     },
            // },
        },
        optimizeDeps: {
            include: [
                'react',
                'react-dom',
                'react-router-dom',
                'gsap',
                'i18next',
                'prismjs',
            ],
        },
        resolve: {
            alias: {
                src: resolve('./src'),
                lib: resolve('./src/lib'),
                utils: resolve('./src/lib/utils'),
                components: resolve('./src/components'),
                app: resolve('./src/app.js'),
                dat: resolve('./src/lib/dat.gui.stats.js'),
                css: resolve('./src/css'),
                api: resolve('./src/api'),
                static: resolve('./src/static'),
            },
        },
        build: {
            target: 'modules', // 'es2015'
            minify: useMinify ? 'terser' : false, // false | 'terser' | 'esbuild'
            terserOptions: {
                compress: {
                    dead_code: true,
                    drop_console: false,
                    unused: true,
                },
                mangle: {
                    toplevel: true,
                },
                ie8: false,
                warnings: false,
                output: {
                    comments: false,
                },
            },
            sourcemap: false,
            cssCodeSplit: false,
            emptyOutDir: true,
            chunkSizeWarningLimit: 1500,
            // assetsDir: 'build',
            outDir: resolve('./dist'),
            rollupOptions: {
                input: resolve('./src/index.html'),
                output: {
                    entryFileNames: '[name].js',
                    assetFileNames: '[name].[ext]',
                    chunkFileNames: '[name].js',
                },
            },
        },
        plugins:
            env == 'dev'
                ? pluginArr
                : [
                      splitVendorChunkPlugin(),
                      svgr(),
                      removePlugin(),
                      docScssPlugin(env),
                      htmlPlugin(),
                      endPlugin(),
                  ],
        define: {
            __ASSETS_URL__: JSON.stringify(assetsURL), // 注入到全局
        },
    });
};
